﻿using System;
using System.Configuration;
using System.Data;
using mojoPortal.Net;
using mojoPortal.Web;
using Resources;
using mojoPortal.Web.Editor;
using mojoPortal.Web.Framework;
using System.Collections;
using mojoPortal.Business;
using ud_gSDMS.Code_Service;
using mojoPortal.Business.WebHelpers;
using System.Web.UI.WebControls;
namespace ud_gSDMS.project
{
    public partial class plan : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        private string _id;
        //private string _idnew;
        private SiteUser siteUser;
        private int currentUserID = 0;
        private static int project_id = Convert.ToInt32(project_id);
        void Page_Load(object sender, EventArgs e)
        {
            siteUser = SiteUtils.GetCurrentSiteUser();
            //if (!UserCanEditPage() || !UserCanViewPage())
            //{
            //    WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
            //}
            if ( SiteUtils.GetCurrentSiteUser() == null)
            {
                WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
            }
            //hidId.Value = _id;
            if (!Page.IsPostBack)
            {
                PopulateLabels();
                PopulateControls();
                if (!string.IsNullOrEmpty(Request["id"]))
                {
                    _id = Request["id"];
                    LoadGridMember(_id);
                    LoadData(_id);
                    LoadGridProjectPlan();
                }
            }
        }
        private void PopulateLabels()
        {

        }
        private void LoadGridMember(string id)
        {
            var data = gSDMS_BL.getMemberList(id);
            grdMember.DataSource = data;
            grdMember.DataBind();
            cboMember.DataSource = data;
            cboMember.DataValueField = "UserID";
            cboMember.DataTextField = "LoginName";
            cboMember.DataBind();

        }
        private void PopulateControls()
        {
            var db = new gSDMS_DataLinq();
            cboWork.DataSource = Library.LINQToDataTable(db, db.ud_gSDMS_CAT_PROJECT_STEPs);
            cboWork.DataValueField = "CAT_Project_Step_ID";
            cboWork.DataTextField = "Name";
            cboWork.DataBind();
           
            //cboMember.DataValueField = "UserID";
            //cboMember.DataTextField = "LoginName";
            //cboMember.DataSource = gSDMS_BL.getMemberList(_id);
            //cboMember.DataBind();

            const bool readOnly = true;
            txtProject_Code.ReadOnly = readOnly;
            txtProject_name.ReadOnly = readOnly;
            cboProject_leader.Enabled = !readOnly;
            txtMan_day.ReadOnly = readOnly;
            datKickoff_Date.ReadOnly = readOnly;
            datEnd_Date.ReadOnly = readOnly;
            txtFeedBacks.WebEditor.ToolBar = mojoPortal.Web.Editor.ToolBar.Full;
            txtFeedBacks.WebEditor.Height = 200;
       }

        private static string projectid;
        private void LoadData(string id)
        {
            if (string.IsNullOrEmpty(id)) return;
            var db = new gSDMS_DataLinq();
            cboProject_leader.DataValueField = "UserID";
            cboProject_leader.DataTextField = "LoginName";
            cboProject_leader.DataSource = gSDMS_BL.mp_User_Search(null, null, null, null, null, null, 5.ToString());
            cboProject_leader.DataBind();

            var o = gSDMS_BL.ud_gSDMS_PROJECT_Get(id);

            if (o != null)
            {
                projectid = o.Project_ID.ToString();
                hidId.Value = o.Project_ID.ToString();
                if (o.CreatedOn != null) hidCreatedOn.Value = o.CreatedOn.Value.ToShortDateString();
                txtProject_Code.Text = o.ud_gSDMS_CONTRACT.Contract_Code;
                txtProject_name.Text = o.Name;
                cboProject_leader.SelectedValue = o.Project_Leader.ToString();
                datKickoff_Date.Text = o.Kickoff_Date.Value.Day+"/"+o.Kickoff_Date.Value.Month+"/"+o.Kickoff_Date.Value.Year;
                datEnd_Date.Text = o.End_Date.Value.Day+"/"+o.End_Date.Value.Month+"/"+o.End_Date.Value.Year;
                txtMan_day.Text = o.Resource.ToString();//lay tu nguon nhan luc thuc te
                //load feedback neu co roi
                DataTable tb = gSDMS_BL.GetFeedBackProjectPlan(projectid);
                if (tb.Rows.Count > 0)
                {
                    txtFeedBacks.Text = tb.Rows[0][0].ToString();
                }
                txtFeedBacks.WebEditor.ToolBar = ToolBar.SimpleWithSource;
            }
        }
        #region event
        void btnSaveandSend_Click(object sender, EventArgs e)
        {
            cboMember.CausesValidation = false;
            cboWork.CausesValidation = false;
            if (!string.IsNullOrEmpty(projectid))
            {
                //update lai CAT_Project_Plan_Status_ID = 'Replan' and save feedBack Comment
                //gSDMS_BL.ud_gSDMS_PROJECT_UpdStatusSendFeedBack(ref projectid, 3.ToString());
                var Project_Plan_ID = string.Empty;
                DataTable tb = (DataTable)ViewState["listprojectplanfeedback"];
                string projectplan_id;
                foreach (DataRow row in tb.Rows)
                {
                    if (row["Project_Plan_ID"] != null) Project_Plan_ID = row["Project_Plan_ID"].ToString();
                    projectplan_id = row["Project_ID"].ToString();
                    if (projectplan_id == projectid)
                    {
                        gSDMS_BL.ud_gSDMS_PROJECT_PLAN_updFeedBack(Project_Plan_ID, txtFeedBacks.Text);
                    }
                }
                    //viet ham gui mail cho GDDA nhac duyet 
                    var userManager = gSDMS_BL.mp_User_get(cboProject_leader.SelectedValue, null);
                    //var emailFrom = siteUser.Email;
                    var to = gSDMS_BL.mp_User_getProjectDir(projectid);
                    var cc = gSDMS_BL.mp_User_Lst("12");

                    string emailCc = "";
                    foreach (var p in cc)
                    {
                        emailCc += p.Email + ",";
                    }
                    //var assigned = gSDMS_BL.mp_User_get(cboAssign_To.SelectedValue, null);
                    
                    //var emailTo = gSDMS_BL.ud_gSDMS_PROJECT_Get(projectid).ud_gSDMS_CONTRACT.mp_User1.Email;
                    var subject = string.Format("[gSDMS-Project Plan] APPROVE IN PROJECT : {0} FROM gSDMS", txtProject_name.Text);
                    var textBody = "<b>From: </b>" + userManager.Name + " [mailto: ] " + userManager.Email + "]" +
                               "<br/><b>Send: </b>" +
                               DateTime.Now.ToLongDateString() + "<br/><b>To: </b>" +
                               to.Name + "; " + to.Email + "<br/><b>Subject: </b>" +
                               txtProject_name.Text + "_Approve<br/><br/><b>Dear </b>" + to.LoginName +
                               ",<br/><br/>Please accept this project: " + txtProject_Code.Text +
                               "<br/><br/> Please click here to approve : " + SiteRoot +
                               "/gsdmsmodule/project/project_detail.aspx?pageid=16&id=" + projectid +
                               "<br/><br/>Thanks you very much!<br/><br/>Regard...!<br/>" + userManager.Name;
                               var siteGuid = siteSettings.SiteGuid;
                               Library.SendMail(userManager.Email, to.Email, emailCc, string.Empty, subject, textBody, siteGuid);
                    //va chuyen tinh trang du an sang wait approve
                         gSDMS_BL.ud_gSDMS_PROJECT_updStatus(projectid);
                    lblMes.Text = "Đã cập nhật lại status = 'Wait Approve' và gửi mail cho PM";
                    lblMes.Visible = true;
                //Response.Redirect("/gSDMSModule/project/manage.aspx");
            } 
        }

        float totalHours = 0;
        void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                _id = hidId.Value;
                //Req
                var userSite = SiteUtils.GetCurrentSiteUser();
                gSDMS_BL.ud_gSDMS_PROJECT_PLAN_upd(ref projectplan_id, _id, cboWork.SelectedValue, cboMember.SelectedValue, txtWork_Description.Text,
                    dateFrom_DateProject.SelectedDate != null ? dateFrom_DateProject.SelectedDate.Value.ToShortDateString() : null,
                    dateTo_DateProject.SelectedDate != null ? dateTo_DateProject.SelectedDate.Value.ToShortDateString() : null,
                    txtDays.Text, txtHours.Text, null, SiteUtils.GetCurrentSiteUser().UserId.ToString(), DateTime.Now.ToShortDateString());
                if (!string.IsNullOrEmpty(hidId.Value))
                {
                    //lblMes.Text = "Updated!";
                    //lblMes.Visible = true;
                    LoadGridProjectPlan();
                    projectplan_id = null;
                    dateFrom_DateProject.SelectedDate = null;
                    dateTo_DateProject.SelectedDate = null;
                    txtWork_Description.Text = "";
                    txtDays.Text = "";
                    txtHours.Text = "";
                }
                else
                {
                    //lblMes.Text = "Inserted!";
                    //lblMes.Visible = true;
                    LoadGridProjectPlan();
                    dateFrom_DateProject.SelectedDate = null;
                    dateTo_DateProject.SelectedDate = null;
                    txtWork_Description.Text = "";
                    txtDays.Text = "";
                    txtHours.Text = "";
                    // Response.Redirect("/gsdmsmodule/contract/contract_cat.aspx");
                }

            }
            catch (Exception ex)
            {
                lblMes.Text = ex.Message;
                lblMes.Visible = true;
            }
        }

        private void LoadGridProjectPlan()
        {
            DataTable data = gSDMS_BL.ud_gSDMS_PROJECT_PLAN_Load(projectid);
            grdProjectPlan.DataSource = data;
            grdProjectPlan.DataBind();
            ViewState["listprojectplanfeedback"] = data;
            for (int i = 0; i < grdProjectPlan.Rows.Count; i++)
            {
                totalHours = totalHours + float.Parse(data.Rows[i]["Hours"].ToString());
            }
            lbHours.Text = " : " + Math.Round(totalHours, 2).ToString();
            lbDays.Text = " : " + Math.Round(totalHours / 8, 2).ToString();
            lbMonth.Text = " : " + Math.Round(totalHours /(8*24), 2).ToString();
        }

        private static string projectplan_id;
        private void grdProjectPlan_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "edit")
            {
                var o = gSDMS_BL.ud_gSDMS_PROJECT_PLAN_UpLoad(e.CommandArgument.ToString());
                projectplan_id = o.Project_Plan_ID.ToString();
                cboMember.SelectedValue = o.UserID.ToString();
                cboWork.SelectedValue = o.CAT_Project_Step_ID.ToString();
                txtWork_Description.Text = o.Work_Description;
                dateFrom_DateProject.SelectedDate = o.From_Date;
                dateTo_DateProject.SelectedDate = o.To_Date;
                txtDays.Text = o.Days.ToString();
                txtHours.Text = o.Hours.ToString();
            }
            else if (e.CommandName == "delete")
            {
                gSDMS_BL.ud_gSDMS_Project_Plan_Del(e.CommandArgument.ToString(), true);
                LoadGridProjectPlan();
            }
        }

        private void grdProjectPlan_RowEditing(object sender, GridViewEditEventArgs e)
        {

        }

        void grdProjectPlan_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            LoadGridProjectPlan();
        }

        void grdProjectPlan_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (ViewState["Direction"] == null) ViewState["Direction"] = " DESC";
            else if (ViewState["Direction"].ToString() == " ASC") ViewState["Direction"] = " DESC";
            else if (ViewState["Direction"].ToString() == " DESC") ViewState["Direction"] = " ASC";
            grdProjectPlan.EditIndex = -1;
            string strSortExp = e.SortExpression + ViewState["Direction"].ToString();
            ViewState["SortExpression"] = strSortExp;
            LoadGridProjectPlan();
        }
        #endregion event

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
            Load += Page_Load;
            SiteUtils.SetupEditor(txtFeedBacks);
        }

        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);
            btnSave.Click += btnSave_Click;
            btnSaveandSend.Click += btnSaveandSend_Click;
            grdProjectPlan.RowCommand += grdProjectPlan_RowCommand;
            grdProjectPlan.RowDeleting += grdProjectPlan_RowDeleting;
            grdProjectPlan.RowEditing += grdProjectPlan_RowEditing;
            grdProjectPlan.Sorting += grdProjectPlan_Sorting;
            SuppressPageMenu();
        }
        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);
        }

        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            //config = new ContactFormConfiguration(settings);
            bool showLeftColumnAdmin = ConfigHelper.GetBoolProperty("ShowLeftColumnAdmin", false);
            bool showRightColumnAdmin = ConfigHelper.GetBoolProperty("ShowRightColumnAdmin", false);
            bool showTopColumnAdmin = ConfigHelper.GetBoolProperty("ShowTopColumnAdmin", false);
            bool showBottomColumnAdmin = ConfigHelper.GetBoolProperty("ShowBottomColumnAdmin", false);
            int showCenterColumnAdmin = ConfigHelper.GetIntProperty("ShowCenterColumnAdmin", 0);
            LoadSideContent(showLeftColumnAdmin, showRightColumnAdmin, showTopColumnAdmin, showBottomColumnAdmin, showCenterColumnAdmin);
        }
        #endregion

        protected void txtContract_Code_TextChanged(object sender, EventArgs e)
        {

        }
    }
}